﻿$(function () {
    var serializer = new JSONSerializer();
    var dict = new Dict();
    var validate = new Validate();
    //绑定证件类型
    var getCardType = dict.GetDictDDLByType(16);
    $(".txtCertificateType").html(getCardType);

    //获取职位分类
    $.ajax({
        type: "post",
        url: "../Handler/DictHandler.ashx",
        dataType: "json",
        data: { Type: 6, DictType: 24, _: Math.random() },
        async: false,
        cache: false,
        complete: function () { },
        success: function (result) {
            if (result.Status) {
                var str = '<option value="-1">请选择</option>';
                $.each(result.Data, function (index, item) {
                    str += '<option value="' + item.DictId + '">' + item.DictName + '</option>';
                });
                $(".txtPositionType").html(str);
            }
            else {
                alert(result.Message);
            }

        }
    });

    //根据职位分类获取具体职位信息
    $(".txtPositionType").change(function () {
        var positionGroup = $(".txtPositionType").val();
        if (positionGroup != -1) {
            //绑定职位信息类型
            var getCardType = dict.GetDictDDLByTypePId("error", positionGroup);
            $(".txtPosition").html(getCardType);
            return;
        }
        $(".txtPosition").html('<option value="-1">请选择</option>');
    });

    var url = new Url();
    var $Id = url.GetQueryString("id");
    var $css = url.GetQueryString("css");
    if ($Id) {//编辑模式，获取并绑定操作用户
        $.getJSON("../Handler/Operator.ashx",
            { Id: $Id, type: 4, _: Math.random() },
            function (result) {
                if (result.Status) {
                    //职位类型单独绑定
                    $(".txtPositionType").val(result.Data.PositionGroup);
                    if ($(".txtPositionType").val() != -1) {
                        $(".txtPositionType").change();
                    }
                    serializer.DeSerialize($("#formArea"), result.Data);
                    //入职日期、离职日期单独处理
                    if (result.Data.EntryDate) {
                        $("#txtEntryDate").val(result.Data.EntryDate);
                        $("#dtp_EntryDate").val(result.Data.EntryDate);
                    }
                    if (result.Data.QuitDate) {
                        $("#txtQuitDate").val(result.Data.QuitDate);
                        $("#dtp_QuitDate").val(result.Data.QuitDate);
                    }
                    //角色
                    var roles = result.Data.Roles;
                    if (roles) {
                        var nameList = new Array();
                        var idList = new Array();
                        $(roles).each(function (index, item) {
                            nameList.push(item.RoleName);
                            idList.push(item.RoleId);
                            $("#chk" + item.RoleId).attr("checked", "true");
                        });
                        $(".txtRole").text(nameList.join(","));
                        $(".hdRoles").val(idList.join(","));
                        $(".btnSelRole").html("修改角色");
                    }
                    else {
                        $(".txtRole").text("您还未选择角色");
                        $(".btnSelRole").html("请选择");
                    }
                    //部门
                    $(".txtDep").text(result.Data.DepName);
                    $(".hdDeps").val(result.Data.DepId);
                }
                else {
                    alert(result.Message);
                }
            });
    }



    //加载部门信息
    $(".btnSelDep").one('click', function () {
        $.getJSON("../Handler/DeptHandler.ashx", { type: 11, _: Math.random() }, function (result) {
            if (result.Status) {
                $('#jstree').jstree({
                    'core': { 'data': result.Data }
                });
                $('#jstree').on("ready.jstree", function (e, data) {
                    var idstr = $(".hdDeps").val();
                    if ($Id && idstr) {
                        var array = idstr.split(",");
                        for (var i = 0; i < array.length; i++) {
                            $.jstree.reference('#jstree').select_node(array[i]);
                        }
                    }
                });
                $('#jstree').on("changed.jstree", function (e, data) {
                    $('.txtDep').text(data.instance.get_node(data.selected).text);
                    $(".hdDeps").val(data.selected);
                });
            }
            else {
                alert(result.Message);
            }
        });
    });
    //搜索
    $(".btnSearch").bind("click", function () {
        var $name = $(".txtSearch").val();
        $.getJSON("../Handler/RoleHandler.ashx",
            { type: 10, Name: $name, _: Math.random() },
            function (result) {
                $(".role_xiangxi").empty();
                if (result.Status) {
                    $(result.Data).each(function (index, item) {
                        $("#RoleTemplete").tmpl(item).appendTo($(".role_xiangxi"));
                    });
                }
                else {
                    alert(result.Message);
                };
            }
        );
    }).click();
    //加载角色信息
    $(".btnSelRole").click(function () {
        var roles = $(".hdRoles").val();
        var array = roles.split(",");
        if (array) {
            $(".role_xiangxi :checkbox").each(function () {
                this.checked = array.indexOf($(this).val()) >= 0;
            });
        }
    });
    //确定
    $(".btnConfirm").bind("click", function () {
        var nameList = new Array();
        var idList = new Array();
        $(".role_xiangxi :checkbox:checked").each(function () {
            nameList.push($(this).attr("data-name"));
            idList.push($(this).val());
        });
        $(".txtRole").text(nameList.join(",")).css("color", "#555");
        $(".hdRoles").val(idList.join(","));
    });

    //错误信息清除
    $("#formArea .txtRequire").blur(function () {
        if ($(this).val().length > 0 || $(this).val() > 0) {
            $(this).next().text("");
        }
    });
    $("#formArea .txtWorkEmail").blur(function () {
        $(".errorWorkEmail").text("");
        if ($(this).val() != "") {
            if (!validate.CheckEmail($(this).val())) {
                $(".errorWorkEmail").text("无效的电子邮箱");
                return false;
            }
        }
    });



    //保存
    var $CertificateType = $("#formArea select[name='CertificateType']");
    var $IDCard = $("input[name='IDCard']");
    var $Email = $("#formArea .txtWorkEmail");

    $(".btnSave").bind("click", function () {

        $("span.error").text("");
        var flag = false;
        //必填项验证
        $('#formArea .txtRequire').each(function (index, item) {
            if ($(this).val().length == 0 || $(this).val() < 0) {
                flag = true;
                $(this).next().text(($(this).attr('data-name') + "不能为空"));
                $(this).focus();
                return false;
            }
        });
        if (flag) {
            return false;
        }

        //身份证号码有效性验证
        if ($CertificateType.val() == "406") {
            var tag = validate.CheckIdCard($IDCard.val());
            if (tag < 0) {
                $IDCard.next("span").text("非法身份证号");
                return;
            }
        }
        //手机号码有效性验证

        if (!validate.CheckPhone($("input[name='Phone']").val())) {
            $("input[name='Phone']").next("span").text("无效的手机号码！");
            $("input[name='Phone']").focus();
            return false;
        }

        if ($("input[name='OptRoles']").val().length == 0) {
            $(".txtRole").text("您还未选择角色");
            $(".txtRole").css("color", "red");
            return;
        }

        if ($("input[name='Dep']").val().length == 0) {
            $(".txtDep").text("您还未选择部门");
            $(".txtDep").css("color", "red");
            return;
        }

        //工作邮箱有限性验证
        if ($Email.val() != "") {
            if (!validate.CheckEmail($Email.val())) {
                $(".errorWorkEmail").text("无效的电子邮箱");
                return false;
            }
        }

        var $formData = serializer.Serialize($("#formArea")[0]);
        $formData.type = $Id && !isNaN($Id) ? 2 : 1;
        if ($Id && !isNaN($Id)) {
            $formData.Id = $Id;
        }
        $formData._ = Math.random();
        $.getJSON("../Handler/Operator.ashx", $formData, function (result) {
            if (result.Status) {
                location.href = "OperatorList.aspx?css=" + $css;
            }
            else {
                alert(result.Message);
            }
        });
    });

    $(".txtName").change(function () {
        $(".errorName").text("");
    });

    $(".txtUserName").change(function () {
        $(".errorUserName").text("");
    });

    //直属上级查询
    $(".btnSuperior").bind("click", function () {

        var depId = $("#hdDeps").val();
        if (depId == "" || depId < 0) {
            alert("请您先选择所属部门!");
            return false;
        }
        var username = $(".txtSuperName").val();
        var phone = $(".txtSuperPhone").val();
        $.getJSON("../Handler/Operator.ashx",
            { type: 16, UserName: username, Phone: phone, Dep: depId, ParentOptId: $Id, _: Math.random() },
            function (result) {
                if (result.Status) {
                    $(".tbSuperInfo").empty();
                    $(result.Data).each(function (index, item) {
                        //前段过滤掉自己
                        if ($Id != item.OptId) {
                            $("#SuperiorTemple").tmpl(item).appendTo($(".tbSuperInfo"));
                        }

                    });
                }
                else {
                    alert(result.Message);
                };
            }
        );
    });

    //选定直属上级
    $("input.txtParentOptName").focus(function () {
        $(".btnShow").trigger("click");
    });

    $(".tbSuperInfo").on("click", ".trSuperior", function () {
        $("input[name='ParentOptId']").val($(this).find(".optId").text());
        $("input.txtParentOptName").val($(this).find(".name").text());
        $("#btnSuperClose").click();
    });


});


//获取本地时间
function getLocalTime(nS) {
    var date = new Date(parseInt(/\d+/.exec(nS)));
    var result = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
    return result;
}